import React, { useState, useEffect } from 'react';
import { TjContent, TjFilter, TjHeader } from '@/tjComponents';
import { Button, DatePicker, Select, Drawer, Spin, message } from 'antd';
import { connect } from 'umi';
// @ts-ignore
import { TjTable, TjDimension } from '@/pages/ETrade/components';
import { useSetState } from 'ahooks';
import {
  buildExportData,
  buildTableData,
  dimensionOptions,
  dimensionValus,
  marketList,
} from './helper';
// @ts-ignore
import { useExcel } from '@/hooks';
import AccountList from './components/AccountList';
import Charts from './components/Charts';
import { getRegionList, queryViewData, queryViewDataForEveryDay } from './service';
import { HttpCode } from '#/utils/contacts.js';
import moment from 'moment';
import { useTablePipeline, features } from 'ali-react-table';
import _ from 'lodash';
import './index.less';
import { useForm } from 'antd/es/form/Form';
import TRDefault from '@/tool/components/TRTheme/TRDefault';

const { RangePicker } = DatePicker;

const initValue = {
  marketId: 'PXBXJ',
  regionIds: ['all'],
  time: [
    moment().startOf('month'),
    moment().date() === 1 ? moment() : moment().subtract(1, 'days'),
    // moment(),
  ],
};

const LongTermAllocationFactor: React.FC<ILongTermAllocationFactorProps> = (props) => {
  const [form] = useForm();
  const [dimensionVal, setDimensionVal] = useState<string[]>(['区域', '风电场', '时间']);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [columns, setColumns] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [regionList, setRegionList] = useState<any[]>([]);
  const [newRegionList, setNewRegionList] = useState<any[]>([]);
  const [initFilterValue, setInitFilterValue] = useState<any>(null);
  const [accountListVisible, setAccountListVisible] = useState<boolean>(false);
  const [xAxisData, setXAxisData] = useState<string[]>([]);
  const [chartsDataObj, setChartsDataObj] = useState<Record<string, any>>();
  const [chartsLoading, setChartsLoading] = useState<boolean>(false);
  const [openKeys, onChangeOpenKeys] = useState<any[]>([0]);
  const [chartsIsMaintained, setChartsIsMaintained] = useState<string[]>([]);

  // const filterOptionObj = useRef<any>({});
  // const chartsDataObj = useRef<any>({});
  // const [chartFilterValus, setChartFilterValus] = useState<string[]>([]);

  const [req, setReq] = useSetState<any>({
    marketId: marketList[0].value,
    startDate: '',
    endDate: '',
    // order: dimensionVal,
  });
  const [chartReq, setChartReq] = useSetState<any>({
    regionId: '',
    startDate: initValue.time[0],
    endDate: initValue.time[1],
  });

  const init = () => {
    setLoading(true);
    setChartsLoading(true);
    getRegionList(req.marketId)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const data = [
            {
              label: '全部区域',
              value: 'all',
            },
            ...res.data,
          ];

          setRegionList(res.data || []);
          setNewRegionList(data);
          const firstRegionId = res.data && res.data.length > 0 ? [res.data[0].value] : [];
          setInitFilterValue({
            ...initValue,
          });
          setReq({
            marketId: initValue.marketId,
            regionIds: initValue.regionIds,
            startDate: moment(initValue.time[0]).format('YYYY-MM-DD'),
            endDate: moment(initValue.time[1]).format('YYYY-MM-DD'),
            order: dimensionOptions,
          });
          setChartReq({
            regionId: firstRegionId[0],
            startDate: moment(initValue.time[0]).format('YYYY-MM-DD'),
            endDate: moment(initValue.time[1]).format('YYYY-MM-DD'),
          });
        } else {
          message.error(res.message);
          setLoading(false);
          setChartsLoading(false);
        }
      })
      .catch(() => {
        setLoading(false);
        setChartsLoading(false);
      });
  };

  const query = () => {
    const params = {
      ...req,
      order: req.order.map((v: string) => dimensionValus[v]),
    };
    if (req.regionIds.indexOf('all') > -1 || !req.regionIds || req.regionIds.length === 0) {
      params.regionIds = regionList.map((v) => v.value);
    }

    setLoading(true);
    queryViewData(params)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const { columns, dataSource, filterOption, chartDatas } = buildTableData(
            res.data.data,
            res.data.head,
            res.data.isMaintained,
          );
          // const listVal = buildChartOptions(filterOption, chartDatas);
          // const chartsKey = findCurrentChartKeys(listVal);
          // filterOptionObj.current = filterOption;
          // chartsDataObj.current = chartDatas;
          // setChartFilterValus(listVal);
          // setXAxisData(res.data.head);
          // setSeries(chartDatas[chartsKey]);
          setColumns(columns);
          setDataSource(dataSource);
          // if (dataSource && dataSource.length > 0) {
          //   onChangeOpenKeys([dataSource[0].id]);
          // }
        } else {
          message.error(res.message);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const queryCharts = () => {
    setChartsLoading(true);
    queryViewDataForEveryDay(chartReq)
      .then((res: any) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const data = _.get(res, 'data.data', null);
          const isMaintained = _.get(res, 'data.isMaintained', []);
          if (data) {
            const xAxis = [];
            const chartObj: any = {};
            // const obj = sortObj(data);
            // for (const [i] of obj) {
            //   xAxis.push(i);
            //   if (data[i]) {
            //     const item = data[i];
            //     const entries = sortObj(item);
            //     for (const [key, value] of entries) {
            //       if (!chartObj[key]) {
            //         chartObj[key] = [];
            //       }
            //       chartObj[key].push(value);
            //     }
            //   }
            // }
            for (const i in data) {
              xAxis.push(i);
              if (data[i]) {
                const item = data[i];
                for (const t in item) {
                  if (!chartObj[t]) {
                    chartObj[t] = [];
                  }
                  chartObj[t].push(item[t]);
                }
              }
            }

            setXAxisData(_.reverse(_.sortBy(xAxis)));
            setChartsDataObj(chartObj);
            setChartsIsMaintained(isMaintained);
          } else {
            setXAxisData([]);
            setChartsDataObj(undefined);
            setChartsIsMaintained([]);
          }
        } else {
          message.error(res.message);
        }
      })
      .finally(() => {
        setChartsLoading(false);
      });
  };

  const onSearch = (values: any) => {
    searchFn(values);
  };

  const onReset = (values: any) => {
    searchFn(values);
  };

  const searchFn = (values: any) => {
    const startDate =
      values.time && values.time.length > 1 ? moment(values.time[0]).format('YYYY-MM-DD') : '';
    const endDate =
      values.time && values.time.length > 1 ? moment(values.time[1]).format('YYYY-MM-DD') : '';
    setReq({
      marketId: values.marketId,
      regionIds: values.regionIds,
      startDate,
      endDate,
    });

    let regionId = '';
    if (values.regionIds.indexOf('all') > -1) {
      regionId = regionList[0].value;
    } else {
      if (!values.regionIds || values.regionIds.length === 0) {
        regionId = regionList[0].value;
      }
      if (values.regionIds.length >= 1) {
        regionId = values.regionIds[0];
      }
    }
    const chartFilterObj = {
      regionId,
      startDate,
      endDate,
    };
    setChartReq(chartFilterObj);
  };

  const aggregation = () => {
    setReq({ order: dimensionVal });
  };

  const onExport = () => {
    useExcel({
      columns: columns,
      data: buildExportData(dataSource),
      filename: `AGC中长期分配系数`,
    });
  };

  const openAccountList = () => {
    setAccountListVisible(true);
  };

  // const changeChartsOptions = (val: string, index: number) => {
  //   const afterKeys = findOptionsByKey(val, filterOptionObj.current);
  //   let newChartFilterValus = [...chartFilterValus];
  //   newChartFilterValus[index] = val;
  //   newChartFilterValus = newChartFilterValus.slice(0, index + 1).concat(afterKeys);
  //   const chartsKey = findCurrentChartKeys(newChartFilterValus);

  //   setChartFilterValus(newChartFilterValus);
  //   setSeries(chartsDataObj.current[chartsKey]);
  // };

  const changeCharts = (val: string | moment.Moment[], type: 'regionId' | 'time') => {
    if (type === 'regionId') {
      setChartReq({
        regionId: val,
      });
    } else if (type === 'time') {
      setChartReq({
        startDate: moment(val[0]).format('YYYY-MM-DD'),
        endDate: moment(val[1]).format('YYYY-MM-DD'),
      });
    }
  };

  const changeRegionIds = (val: any[]) => {
    const last = val.slice(-1);
    if (last[0] === 'all') {
      form.setFieldsValue({
        regionIds: ['all'],
      });
    } else {
      form.setFieldsValue({
        regionIds: _.remove(val, (n: string) => n !== 'all'),
      });
    }
  };

  useEffect(() => {
    init();
  }, []);

  useEffect(() => {
    if (req.marketId && req.regionIds) {
      query();
    }
  }, [req]);

  useEffect(() => {
    if (chartReq.regionId) {
      queryCharts();
    }
  }, [chartReq]);

  const pipeline = useTablePipeline()
    .input({ dataSource, columns })
    .primaryKey('id')
    .use(features.treeMode({ openKeys, onChangeOpenKeys }));

  return (
    <div className="long-term-allocation-factor">
      <TjHeader
        left={
          <TjFilter
            defaultValues={initFilterValue}
            onReset={onReset}
            onSearch={onSearch}
            loading={loading}
            form={form}
            items={[
              {
                name: 'marketId',
                render: (
                  <Select
                    options={marketList}
                    allowClear={false}
                    style={{ width: 180 }}
                    loading={loading}
                  />
                ),
              },
              {
                name: 'regionIds',
                render: (
                  <Select
                    options={newRegionList}
                    style={{ width: 240 }}
                    loading={loading}
                    mode="multiple"
                    onChange={changeRegionIds}
                  />
                ),
              },
              { name: 'time', render: <RangePicker /> },
            ]}
          />
        }
        right={
          <>
            <Button onClick={openAccountList} type="link" loading={loading}>
              账号列表
            </Button>
            <Button onClick={onExport} type="link" loading={loading}>
              导出
            </Button>
          </>
        }
      />

      <TjContent className="long-term-allocation-factor-content">
        <div className="left">
          <Spin spinning={loading}>
            <div className="dimension">
              <TjDimension
                value={dimensionVal}
                options={dimensionOptions}
                onChange={(order: any[]) => setDimensionVal(order)}
                onPoly={aggregation}
                useEdit={false}
                title="聚合顺序调整"
              />
            </div>
            <div className="table-box">
              {columns.length <= 1 ? (
                <TRDefault type="empty" />
              ) : (
                <TjTable {...pipeline.getProps()} />
              )}
            </div>
          </Spin>
        </div>

        <div className="right">
          <Spin spinning={chartsLoading}>
            <div className="title">AGC中长期分配系数图</div>
            {/* <ChartsOptions
            filterOptions={filterOptionObj.current}
            listVal={chartFilterValus}
            changeChartsOptions={changeChartsOptions}
          /> */}

            <div className="charts-options-box">
              <Select
                options={regionList}
                style={{ width: 150 }}
                value={chartReq.regionId}
                onChange={(val) => changeCharts(val, 'regionId')}
              />
              <RangePicker
                value={[moment(chartReq.startDate), moment(chartReq.endDate)]}
                onChange={(val) => changeCharts(val as moment.Moment[], 'time')}
              />
            </div>

            <div className="charts-box">
              {xAxisData.length <= 0 || !chartsDataObj ? (
                <TRDefault type="empty" />
              ) : (
                <Charts
                  xAxisData={xAxisData}
                  chartsDataObj={chartsDataObj}
                  chartsIsMaintained={chartsIsMaintained}
                />
              )}
            </div>
          </Spin>
        </div>
      </TjContent>

      <Drawer
        title="账号列表"
        visible={accountListVisible}
        width={1000}
        onClose={() => setAccountListVisible(false)}
      >
        <AccountList regionList={regionList} />
      </Drawer>
    </div>
  );
};

interface ILongTermAllocationFactorProps {
  menuCode: string;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(LongTermAllocationFactor);
